import AbTestMgr from "./AbTestMgr";
import AdManager, { adPosType } from "./AdManager";
import AudioManager from "./AudioManager";
import BasePageCtrl from "./BasePageCtrl";
import EngineUtil from "./EngineUtil";
import EventMgr from "./EventMgr";
import GameEventType from "./GameEventType";
import GameUtils from "./GameUtils";
import MatchGameData from "./MatchGameData";
import MatchGameEventType from "./MatchGameEventType";
import MatchGameTargetPage from "./MatchGameTargetPage";
import NativeUtils from "./NativeUtils";
import NodePool from "./NodePool";
import { ObstacleAllType, ObstacleTargetName } from "./ObstacleConfig";
import OutsideGuideExperimentMgr from "./OutsideGuideExperimentMgr";
import PageMgr from "./PageMgr";
import PeripheralSystemDataMgr from "./PeripheralSystemDataMgr";
import PeripheralSystemMgr, { OutSideLevelGuide, VideoBuriedPoint } from "./PeripheralSystemMgr";
import PlayerDataSys from "./PlayerDataSys";
import SdkHelper from "./SdkHelper";
import UiManager from "./UiManage";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MatchGameTargetPageCtrl extends BasePageCtrl {
    ui = null;
    targetItemPrefab = null;
    outSideGuideStep = null;
    nodeData = [];
    btn_withdraw = null;

    static prefabUrl = "MatchGameTargetPage";
    static className = "MatchGameTargetPageCtrl";

    onLoad() {
        this.onUILoad();
        this.addButtonListen();
        this.addEvent();
        super.onLoad();
    }

    _init(e?) {
        this.node.setContentSize(cc.winSize);
        this.ui.topNodeParent.removeAllChildren();
        this.nodeData = [];

        const a = PeripheralSystemDataMgr.getGameShowTopNodeArr();
        const o = PeripheralSystemDataMgr.isShowClock();

        for (let i = 0; i < a.length; i++) {
            const {
                type: n,
                topNode: l
            } = a[i];

            l.opacity = 0;
            const s = cc.instantiate(l);
            // s.parent = this.ui.topNodeParent;
            const c = s.getComponent(cc.Button);
            s.getComponent(cc.Widget) && (s.getComponent(cc.Widget).enabled = false);

            // if ("cashNode" == s.name) {
            //     c && (c.interactable = true);
            //     UiManager.addButtonListen(s, this.clickWithDraw, this);
            // }

            // if ("fundNode" == s.name) {
            //     c && (c.interactable = true);
            //     UiManager.addButtonListen(s, this.clickFundWithDraw, this);
            // }

            // if ("btn_day_click" == s.name) {
            //     c && (c.interactable = true);
            //     UiManager.addButtonListen(s, this.clickDay, this);
            //     s.active = o && l.active;
            // }

            // if ("topNode" == s.name) {
            //     c && (c.interactable = true);
            //     UiManager.addButtonListen(s, this.clickTicket, this);
            // }

            this.scheduleOnce(() => {
                s.setPosition(cc.v3(EngineUtil.getNodeAToNodeBPoint(l, s)));
                s.opacity = 255;
                if (i == a.length - 1) {
                    this.checkCanWithDraw();
                }
            });
            this.nodeData.push({
                topNode: s,
                type: n
            });
        }

        this.ui.lab_game_level.getComponent(cc.Label).string = "第" + e.level + "关";

        this.outSideGuideStep = e.guide_step;
        if (e.guide_step == OutSideLevelGuide.BREAKTHROUGH) {
            this.ui.btn_close.active = false;
        } else {
            this.ui.btn_close.active = true;
        }

        this.initTarget(e.target);

        PeripheralSystemDataMgr.setRollingNoticeParent(this.ui.noticeParent);
        this.updateClockShow();
    }

    addEvent() {
        EventMgr.listen(GameEventType.GAME_START_TOP_CASH, this.updateTopCash, this);
        EventMgr.listen(GameEventType.GAME_TOP_CLOCK_SHOW, this.updateClockShow, this);
    }

    removeEvent() {
        EventMgr.ignore(GameEventType.GAME_START_TOP_CASH, this.updateTopCash, this);
        EventMgr.ignore(GameEventType.GAME_TOP_CLOCK_SHOW, this.updateClockShow, this);
    }

    updateTopCash() {
        const e = this.getTopNodeByType(1);
        if (e) {
            const t = e.getChildByName("cashCount");
            if (t) {
                t.getComponent(cc.Label).string = EngineUtil.getCashBalance(PlayerDataSys.cash_balance) + "";
                this.checkCanWithDraw();
            } else {
                console.log("展示红包数量的节点不存在");
            }
        } else {
            console.log("关卡开始前的顶部节点获取错误请检查");
        }
    }

    getTopNodeByType(e) {
        for (let t = 0; t < this.nodeData.length; t++) {
            const {
                type: a,
                topNode: o
            } = this.nodeData[t];

            if (a == e) {
                return o;
            }
        }
        return null;
    }

    checkCanWithDraw() {
        const e = PeripheralSystemDataMgr.isCanWithDraw();
        const t = this.getTopNodeByType(1);
        if (t) {
            const a = t.getChildByName("btn_payment");
            const o = t.getChildByName("btn_canPay");
            if (a && o) {
                this.btn_withdraw = o;
                if (e) {
                    PeripheralSystemDataMgr.checkShowPayMent();
                    a.active = false;
                    o.active = true;
                } else {
                    a.active = true;
                    o.active = false;
                }
            } else {
                console.log("可打款按钮显示错误");
            }
        } else {
            console.log("关卡开始前的顶部节点获取错误请检查");
        }
    }
    onUILoad() {
        this.ui = this.node.addComponent(MatchGameTargetPage);
    }

    async initTarget() {
        let checkContinue = async (e: number): Promise<boolean> => {
            for (const e in targetInfo) {
                const target = targetInfo[e];
                const {
                    squareType: r,
                    itemType: i,
                    tootalCount
                } = target;

                if (Number(r) === 3 && i === ObstacleAllType.Grass && isHasGrassLand) {
                    continue;
                }

                if (Number(r) === 3 && i === ObstacleAllType.PurpleFlower && isHasFlowerpot) {
                    continue;
                }

                // const node = NodePool.getNode("target2_item_pool");
                // this.ui.targetLayout.addChild(node);

                // const img = node.getChildByName("img_target") as cc.Node;
                // img.opacity = 0;
                // const targetCount = node.getChildByName("target_count") as cc.Node;
                // targetCount.opacity = 0;

                // const path = getTargetImgPath(target);
                // await UiManager.loadSpriteFrameInDeepPath(img.getComponent(cc.Sprite), path);

                // await new Promise<void>((resolve) => {
                //     this.scheduleOnce(() => {
                //         const scale = img.height > img.width ? 70 / img.height : 70 / img.width;
                //         img.scale = scale;
                //         resolve();
                //     });
                // });

                // targetCount.getComponent(cc.Label).string = "X" + tootalCount;
            }
            return false;
        }

        let getTargetImgPath = (e): string => {
            var t = "imgs/game/obstacle/", a = e.squareType, o = e.itemType;
            if (1 == Number(a)) t = "imgs/game/matchItem/Items-MatchItem-" + o; else if (3 == Number(a)) switch (o) {
                case ObstacleAllType.WoodenBox:
                    t += ObstacleTargetName.WoodenBox;
                    break;

                case ObstacleAllType.ColorBox:
                    t += ObstacleTargetName.ColorBox;
                    break;

                case ObstacleAllType.Grass:
                    t += ObstacleTargetName.Grass;
                    break;

                case ObstacleAllType.GrassLand:
                    t += ObstacleTargetName.GrassLand;
                    break;

                case ObstacleAllType.Egg:
                    t += ObstacleTargetName.Egg;
                    break;

                case ObstacleAllType.ColorBottle:
                    t += ObstacleTargetName.ColorBottle;
                    break;

                case ObstacleAllType.Vase:
                    t += ObstacleTargetName.Vase;
                    break;

                case ObstacleAllType.Honey:
                    t += ObstacleTargetName.Honey;
                    break;

                case ObstacleAllType.Icicle:
                    t += ObstacleTargetName.Icicle;
                    break;

                case ObstacleAllType.curtain:
                    t += ObstacleTargetName.curtain;
                    break;

                case ObstacleAllType.Pearl:
                case ObstacleAllType.Oyster:
                    t += ObstacleTargetName.Pearl;
                    break;

                case ObstacleAllType.Flowerpot:
                    t += ObstacleTargetName.Flowerpot;
                    break;

                case ObstacleAllType.Stone:
                    t += ObstacleTargetName.Stone;
                    break;

                case ObstacleAllType.SafeBox:
                    t += ObstacleTargetName.SafeBox;
                    break;

                case ObstacleAllType.PorcelainPig:
                    t += ObstacleTargetName.PorcelainPig;
                    break;

                case ObstacleAllType.cupboard:
                    t += ObstacleTargetName.cupboardPlate;
                    break;

                case ObstacleAllType.MagicHat:
                    t += ObstacleTargetName.Gem;
                    break;

                case ObstacleAllType.MailBox:
                    t += ObstacleTargetName.Mail;
                    break;

                case ObstacleAllType.Bird:
                    t += ObstacleTargetName.Bird;
                    break;

                case ObstacleAllType.GoldCoin:
                    t += ObstacleTargetName.GoldCoin;
                    break;

                case ObstacleAllType.PurpleFlower:
                    t += ObstacleTargetName.PurpleFlower;
                    break;

                case ObstacleAllType.Candlebox:
                    t += ObstacleTargetName.Candlebox;
                    break;

                case ObstacleAllType.BirdNest:
                    t += ObstacleTargetName.BirdNest;
                    break;

                case ObstacleAllType.CupHolder:
                    t += ObstacleTargetName.CupHolder;
                    break;

                case ObstacleAllType.Rock:
                    t += ObstacleTargetName.Rock;
                    break;

                case ObstacleAllType.DrillFill:
                    t += ObstacleTargetName.DrillFill;
            }
            return t;
        }

        let loadImage = async (node, target) => {
            const imgTarget = node.getChildByName("img_target");
            imgTarget.opacity = 0;
            const targetCount = node.getChildByName("target_count");
            targetCount.opacity = 0;

            const imgPath = getTargetImgPath(target);
            await UiManager.loadSpriteFrameInDeepPath(imgTarget.getComponent(cc.Sprite), imgPath);

            await this.scheduleOnce(() => {
                const scale = imgTarget.height > imgTarget.width ? 70 / imgTarget.height : 70 / imgTarget.width;
                imgTarget.scale = scale;
            });

            targetCount.getComponent(cc.Label).string = "X" + target.tootalCount;
        }

        this.ui.targetLayout.removeAllChildren();
        if (!MatchGameData.target_info) return;

        if (!this.targetItemPrefab) {
            this.targetItemPrefab = await UiManager.loaderPrefabInDeepPath("prefabs/targetItemPrefab2");
            NodePool.initPool(this.targetItemPrefab, 0, "target2_item_pool");
        }

        const targetInfo = MatchGameData.target_info;
        console.log("初始化目标数据", targetInfo);

        let isHasGrassLand = false;
        let isHasFlowerpot = false;

        for (let i = 0; i < targetInfo.length; i++) {
            const {
                squareType: sType,
                itemType: iType
            } = targetInfo[i];

            if (Number(sType) === 3 && iType === ObstacleAllType.Flowerpot) {
                isHasFlowerpot = true;
            }

            if (Number(sType) === 3 && iType === ObstacleAllType.GrassLand) {
                isHasGrassLand = true;
            }
        }

        // 初始化目标项
        this.ui.targetLayout.removeAllChildren();
        for (let i = 0; i < targetInfo.length; i++) {
            if (await checkContinue(i)) continue;
            const node = NodePool.getNode("target2_item_pool");
            this.ui.targetLayout.addChild(node);
            await loadImage(node, targetInfo[i]);
        }

        this.scheduleOnce(() => {
            this.ui.targetLayout.children.forEach((child) => {
                child.getChildByName("img_target").opacity = 255;
                child.getChildByName("target_count").opacity = 255;
            });
        }, .1);


    }

    addButtonListen() {
        UiManager.addButtonListen(this.ui.btn_close, this.clickClose, this);
        UiManager.addButtonListen(this.ui.btn_startGame, this.startGameCallback, this, 2000);
    }

    startGameCallback() {
        this.checkEndOutsideGuide();

        if (MatchGameData.full_ad_flag) {
            SdkHelper.showForceToast("关卡加载中，广告5秒可关闭");
            if (!EngineUtil.getLocalData("ad_sound_play")) {
                AudioManager.getInstance().playMusic("ad_toast", false);
                EngineUtil.setLocalData("ad_sound_play", "1");
            }

            NativeUtils.showVideoAd(7,() => {
                this.clickClose();
                EventMgr.trigger(MatchGameEventType.LOAD_MATCH_SCENE);
                PeripheralSystemDataMgr.reportVideoBuriedPoint(VideoBuriedPoint.FULL_AD);
            });
        } else {
            this.clickClose();
            EventMgr.trigger(MatchGameEventType.LOAD_MATCH_SCENE);
        }
    }

    clickClose() {
        const topNodes = PeripheralSystemDataMgr.getGameShowTopNodeArr();
        for (let i = 0; i < topNodes.length; i++) {
            const {
                type,
                topNode
            } = topNodes[i];
            topNode.opacity = 255;
        }

        EventMgr.trigger(GameEventType.SET_ROLL_NOTICE_PARENT);
        this.hide();

        if (AbTestMgr.isOptimizeTravelFundFlag()) {
            if (1) {
                if (this.outSideGuideStep === OutsideGuideExperimentMgr.OutSideLevelGuideExperimentStep.CASH_WITHDRAW) {
                    PeripheralSystemDataMgr.setOutsideStep(OutsideGuideExperimentMgr.OutSideLevelGuideExperimentStep.CONTINUE_GAME);
                    PeripheralSystemMgr.reportOutsideGuideStep(OutsideGuideExperimentMgr.OutSideLevelGuideExperimentStep.CONTINUE_GAME);
                }
            } else {
                if (this.outSideGuideStep === OutSideLevelGuide.MOVE_REWARD) {
                    PeripheralSystemDataMgr.setOutsideStep(OutSideLevelGuide.CONTINUE_GAME);
                    PeripheralSystemMgr.reportOutsideGuideStep(OutSideLevelGuide.CONTINUE_GAME);
                }
            }

            if (this.outSideGuideStep === OutSideLevelGuide.FUND_WITHDRAW && 1 === C._gameLevel) {
                SdkHelper.reportData("enter_first_level");
            }
        }
    }

    clickWithDraw() {
        PeripheralSystemMgr.getExtractInfo();
    }

    clickFundWithDraw() {
        PeripheralSystemMgr.getTravelExtractInfo();
    }

    clickDay() {
        PeripheralSystemMgr.getClockTaskList();
    }

    checkEndOutsideGuide() {
        const e = PeripheralSystemDataMgr.getOutsideGuideStep();
        const t = MatchGameData._gameLevel;

        if (AbTestMgr.isOptimizeTravelFundFlag()) {
            if (e === OutsideGuideExperimentMgr.OutSideLevelGuideExperimentStep.CASH_WITHDRAW) {
                PeripheralSystemDataMgr.setOutsideStep(OutsideGuideExperimentMgr.OutSideLevelGuideExperimentStep.CONTINUE_GAME);
                PeripheralSystemMgr.reportOutsideGuideStep(OutsideGuideExperimentMgr.OutSideLevelGuideExperimentStep.CONTINUE_GAME);
            }
        } else {
            if (e === OutSideLevelGuide.MOVE_REWARD) {
                PeripheralSystemDataMgr.setOutsideStep(OutSideLevelGuide.CONTINUE_GAME);
                PeripheralSystemMgr.reportOutsideGuideStep(OutSideLevelGuide.CONTINUE_GAME);
            }
        }

        if (e === OutSideLevelGuide.FUND_WITHDRAW && t === 1) {
            SdkHelper.reportData("enter_first_level");
        }
    }

    updateClockShow() {
        const fundTipNode = this.getTopNodeByType(2).getChildByName("fundTipNode");
        const fundTipsLabel = fundTipNode.getChildByName("fundTipsLabel");
        const currentLocation = PeripheralSystemDataMgr.getCurrentLocation();
        let text = "";
        if (currentLocation >= 11) {
            fundTipNode.active = false;
        } else {
            fundTipNode.active = true;
            if (currentLocation < 5) {
                const steps = 8 - currentLocation;
                text = `<color=#FFFFFF>预计再到达\n</color><color=#FCFF1B>${steps > 0 ? steps : 0}个</color><color=#FFFFFF>城市即可\n</color><color=#FFFFFF>提现</color><color=#FCFF1B>500元</color>`;
                fundTipsLabel.getComponent(cc.RichText).string = text;
            } else {
                text = `<color=#FFFFFF>再赚</color><color=#FCFF1B>${EngineUtil.getCashBalance(50000 - PlayerDataSys.gold_balance)}元\n</color><color=#FFFFFF>可提现</color><color=#FCFF1B>500元</color>`;
                fundTipsLabel.getComponent(cc.RichText).string = text;
            }

            this.playAirBubbleAction(fundTipNode);
        }
    }

    playAirBubbleAction(node) {
        cc.tween(node)
            .to(0.5, { scale: 1.2 })
            .to(0.5, { scale: 1 })
            .call(() => {
                // node.getComponent(cc.Animation).play("airbubble");
            })
            .start();
    }

    clickTicket() {
        PageMgr.showPage("TravelToastPage", {
            type: 1,
            cityId: null
        });
    }
}

